package com.che.software.testato.business;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.che.software.testato.business.exception.IterationSearchManagerException;
import com.che.software.testato.business.exception.IterationUpdateManagerException;
import com.che.software.testato.business.exception.MatrixResultUpdateManagerException;
import com.che.software.testato.domain.dao.IIterationDAO;
import com.che.software.testato.domain.dao.IMatrixResultDAO;
import com.che.software.testato.domain.dao.jdbc.exception.IterationSearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.IterationUpdateDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.MatrixResultUpdateDAOException;
import com.che.software.testato.domain.entity.Iteration;
import com.che.software.testato.domain.entity.MatrixResult;
import com.che.software.testato.domain.entity.search.IterationSearch;
import com.che.software.testato.domain.enumeration.AssignmentStatus;
import com.che.software.testato.domain.enumeration.SelectionTypes;

/**
 * Manager dedicated to the selectives prioritizations.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @since August, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Service("selectivePrioritizationManager")
public class SelectivePrioritizationManager {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(SelectivePrioritizationManager.class);

	/**
	 * Members.
	 */
	@Autowired
	private IIterationDAO iterationDAO;
	@Autowired
	private IMatrixResultDAO matrixResultDAO;

	/**
	 * Performs the selective prioritization for an iteration which has been
	 * analyticaly prioritized.
	 * 
	 * @param currentIterationId the id of the iteration to selectively
	 *        prioritize.
	 * @param selectionType the choosen selection type.
	 * @param costResults the cost results to use for the given iteration.
	 * @param valuesResults the value results to use for the given iteration.
	 * @param fitResults the fit results to use for the given iteration.
	 * @param riskResults to risk results to use for the given iteration.
	 * @throws MatrixResultUpdateManagerException if an error occurs during a
	 *         result update.
	 * @throws IterationSearchManagerException if an error occurs during an
	 *         iteration search.
	 * @throws IterationUpdateManagerException if an error occurs during an
	 *         iteration update.
	 * @since August, 2011.
	 */
	public void prioritize(int currentIterationId, SelectionTypes selectionType, List<MatrixResult> costResults, List<MatrixResult> valuesResults, List<MatrixResult> fitResults, List<MatrixResult> riskResults) throws MatrixResultUpdateManagerException, IterationSearchManagerException, IterationUpdateManagerException {
		LOGGER.debug("prioritize(" + currentIterationId + "," + selectionType.name() + "," + costResults.size() + " scripts).");
		for (int i = 0; i < costResults.size(); i++) {
			if (!isScriptSelected(selectionType, costResults.get(i), valuesResults.get(i), fitResults.get(i), riskResults.get(i))) {
				costResults.get(i).setSelected(false);
				valuesResults.get(i).setSelected(false);
				fitResults.get(i).setSelected(false);
				riskResults.get(i).setSelected(false);
				try {
					matrixResultDAO.updateMatrixResult(costResults.get(i));
					matrixResultDAO.updateMatrixResult(valuesResults.get(i));
					matrixResultDAO.updateMatrixResult(fitResults.get(i));
					matrixResultDAO.updateMatrixResult(riskResults.get(i));
				} catch (MatrixResultUpdateDAOException e) {
					throw new MatrixResultUpdateManagerException(e);
				}
			}
		}
		IterationSearch searchBean = new IterationSearch();
		searchBean.setIterationId(currentIterationId);
		searchBean.setSelectiveStatus(AssignmentStatus.NOT_ASSIGNED);
		try {
			Iteration currentIteration = iterationDAO.searchIteration(searchBean).get(0);
			currentIteration.setSelectiveStringStatus(null);
			currentIteration.setSelectiveStatus(AssignmentStatus.ENDED);
			currentIteration.setSelectionStringType(null);
			currentIteration.setSelectionType(selectionType);
			iterationDAO.updateIteration(currentIteration);
		} catch (IterationSearchDAOException e) {
			throw new IterationSearchManagerException(e);
		} catch (IterationUpdateDAOException e) {
			throw new IterationUpdateManagerException(e);
		}
	}

	/**
	 * Checks if a script is selected after the selective prioritization.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param selectionType the selection type.
	 * @param costResult the cost importance percentage for the given script.
	 * @param valuesResult the value importance percentage for the given script
	 * @param fitResult the fit importance percentage for the given script
	 * @param riskResult the risk importance percentage for the given script
	 * @return true if the script is selected, else false.
	 * @since August, 2011.
	 */
	private boolean isScriptSelected(SelectionTypes selectionType, MatrixResult costResult, MatrixResult valuesResult, MatrixResult fitResult, MatrixResult riskResult) {
		LOGGER.debug("isScriptSelected(" + selectionType.name() + ").");
		switch (selectionType) {
		case DRASTIC:
			return isInHighArea(costResult.getPercentage(), valuesResult.getPercentage()) && isInHighArea(fitResult.getPercentage(), riskResult.getPercentage());
		case ELITIST:
			return !isInLowArea(costResult.getPercentage(), valuesResult.getPercentage()) && !isInLowArea(fitResult.getPercentage(), riskResult.getPercentage());
		case FLEXIBLE:
			return isInHighArea(costResult.getPercentage(), valuesResult.getPercentage()) || isInHighArea(fitResult.getPercentage(), riskResult.getPercentage());
		case SAFE:
			return isInHighArea(costResult.getPercentage(), valuesResult.getPercentage()) || isInHighArea(fitResult.getPercentage(), riskResult.getPercentage()) || isInMediumArea(costResult.getPercentage(), valuesResult.getPercentage()) || isInMediumArea(fitResult.getPercentage(), riskResult.getPercentage());
		case TOTAL:
			return true;
		default:
			return false; // Doesn't happened.
		}
	}

	/**
	 * Checks if a point is in the high area.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param x the x value of the point.
	 * @param y the y value of the point.
	 * @return true if the point is in the high area, else false.
	 * @since August, 2011.
	 */
	private boolean isInHighArea(Double x, Double y) {
		LOGGER.debug("isInHighArea(" + x + "," + y + ").");
		return y > (1.5 * x);
	}

	/**
	 * Checks if a point is in the low area.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param x the x value of the point.
	 * @param y the y value of the point.
	 * @return true if the point is in the low area, else false.
	 * @since August, 2011.
	 */
	private boolean isInLowArea(Double x, Double y) {
		LOGGER.debug("isInLowArea(" + x + "," + y + ").");
		return y <= (0.5 * x);
	}

	/**
	 * Checks if a point is in the medium area.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param x the x value of the point.
	 * @param y the y value of the point.
	 * @return true if the point is in the medium area, else false.
	 * @since August, 2011.
	 */
	private boolean isInMediumArea(Double x, Double y) {
		LOGGER.debug("isInMediumArea(" + x + "," + y + ").");
		return (y > (0.5 * x)) && (y <= (1.5 * x));
	}

	/**
	 * Getter for the private field value matrixResultDAO.
	 * 
	 * @return the matrixResultDAO field value.
	 */
	public IMatrixResultDAO getMatrixResultDAO() {
		return matrixResultDAO;
	}

	/**
	 * Setting a value to the matrixResultDAO field.
	 * 
	 * @param matrixResultDAO the value to set.
	 */
	public void setMatrixResultDAO(IMatrixResultDAO matrixResultDAO) {
		this.matrixResultDAO = matrixResultDAO;
	}

	/**
	 * Getter for the private field value iterationDAO.
	 * 
	 * @return the iterationDAO field value.
	 */
	public IIterationDAO getIterationDAO() {
		return iterationDAO;
	}

	/**
	 * Setting a value to the iterationDAO field.
	 * 
	 * @param iterationDAO the value to set.
	 */
	public void setIterationDAO(IIterationDAO iterationDAO) {
		this.iterationDAO = iterationDAO;
	}
}